package cms.service.upload;

import cms.bean.setting.EditorTag;
import cms.bean.user.AccessUser;
import cms.common.data.ApiResult;
import cms.common.data.ApiResultCode;
import cms.utils.FileUtil;
import cms.utils.UUIDUtil;
import cms.web.action.fileSystem.FileManage;
import cms.manage.SettingManage;
import cms.manage.user.UserRoleManage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;

@Slf4j
public abstract class BaseFileService implements FileService {
    @Resource
    UserRoleManage userRoleManage;

    @Resource
    SettingManage settingManage;

    @Resource
    FileManage fileManage;

    public ApiResult<String> upload(MultipartFile file, AccessUser accessUser, String model, String fileFormat) {
        try {
            doUpload(file, accessUser, model, fileFormat);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("文件操作异常", e);
        }
        return ApiResult.buildFailure(ApiResultCode.SYSTEM_ERROR);
    }

    protected ApiResult<String> doUpload(MultipartFile file, AccessUser accessUser, String model, String fileType) throws Exception {

        UpFileType upFileType = uploadHander(model, accessUser);

        //上传文件编号
        String fileNumber = "b" + accessUser.getUserId();
        //当前文件名称
        String fileName = file.getOriginalFilename();
        //文件大小
        Long size = file.getSize();
        //取得文件后缀
        String suffix = FileUtil.getExtension(fileName).toLowerCase();

        //允许上传图片格式
        List<String> upFormats = upFileType.formats;
        //允许上传图片大小
        long upSize = upFileType.size;

        //验证文件类型
        boolean authentication = FileUtil.validateFileSuffix(file.getOriginalFilename(), upFormats);
        if (authentication) {
            String date = getOpDate();
            if (size / 1024 <= upSize) {
                //文件保存目录;分多目录主要是为了分散图片目录,提高检索速度
                String pathDir = "file" + File.separator + model + File.separator + date + File.separator + fileType + File.separator;
                //文件锁目录
                String lockPathDir = "file" + File.separator + model + File.separator + "lock" + File.separator;
                //构建文件名称
                String newFileName = UUIDUtil.getUUID32() + fileNumber + "." + suffix;

                //生成文件保存目录
                fileManage.createFolder(pathDir);
                //生成锁文件保存目录
                fileManage.createFolder(lockPathDir);
                //生成锁文件
                fileManage.addLock(lockPathDir, date + "_" + fileType + "_" + newFileName);
                //保存文件
                fileManage.writeFile(pathDir, newFileName, file.getBytes());
                //上传成功
//                returnJson.put("error", 0);//0成功  1错误
//                returnJson.put("url", "file/topic/" + date + "/image/" + newFileName);
//                return JsonUtils.toJSONString(returnJson);
                return ApiResult.buildSuccess("file/" + model + "/" + date + "/" + fileType + "/" + newFileName);
            } else {
                return ApiResult.buildFailure(ApiResultCode.PARAM_ERROR.setMessage("上传文件文件超出允许上传大小"));
            }
        } else {
            return ApiResult.buildFailure(ApiResultCode.PARAM_ERROR.setMessage("上传文件当前文件类型不允许上传"));
        }
    }


    /**
     * 上传不同的文件实现这个接口即可
     *
     * @param model
     * @param accessUser
     * @return
     */
    protected abstract UpFileType uploadHander(String model, AccessUser accessUser);

    /**
     * 获取编辑设置
     *
     * @param type
     * @return
     */
    protected EditorTag getEditorTag(String type) {
        if (StringUtils.equals(type, "topic")) {
            return settingManage.readTopicEditorTag();
        }
        return null;
    }

    /**
     * 获取操作时间
     *
     * @return
     */
    private String getOpDate() {
        DateTime dateTime = new DateTime();
        String date = dateTime.toString("yyyy-MM-dd");
        return date;
    }

}
